<template>
  <tm-app :followTheme="true">
    <tm-navbar
      title="活动商品免费拿"
      :followTheme="true"
      :hideHome="true"
      :hideBack="false"
    >
    </tm-navbar>
    <tm-sheet
      :margin="[20]"
      :padding="[20, 20, 20, 20]"
      :round="4"
      _class="flex-center"
    >
      <tm-carousel
        autoplay
        :margin="[0]"
        align="right"
        :round="4"
        :width="getWidth(1)"
        :height="500"
        :list="state.giftInfo.marketingGiftInfo.images"
      ></tm-carousel>
      <tm-text
        _class="my-n10 text-weight-b"
        :label="state.giftInfo.marketingGiftInfo.giftDesc"
      >
      </tm-text>
    </tm-sheet>

    <tm-sheet
      :margin="[20]"
      :padding="[20, 40]"
      :round="4"
      _class="flex-center"
    >
      <tm-text
        _class="text-weight-b text-align-center mb-n10"
        color="indigo"
        :fontSize="40"
        :label="`${'经验值积累满后将免费为您包邮到家'}`"
      >
      </tm-text>
      <view class="flex-center mb-n10">
        <tm-text
          _class="mr-n20"
          :label="`已攒经验值：${
            state.giftInfo.marketingRecordInfo.hasEmpirical || '-'
          }`"
        >
        </tm-text>
        <tm-text
          :label="`所需经验值：${
            state.giftInfo.marketingRecordInfo.giftEmpirical || '-'
          }`"
        >
        </tm-text>
      </view>
      <tm-progress
        :followTheme="true"
        linear="right"
        linearDeep="accent"
        :height="60"
        :round="20"
        :showBar="true"
        :width="getWidth(2)"
        v-model:percent="state.percent"
      ></tm-progress>

      <view class="fulled">
        <!-- 成功的话联系客服 -->
        <tm-button
          :margin="[30]"
          :round="10"
          block
          openType="contact"
          v-if="Number.parseInt(state.percent) == 100"
          :follow-theme="true"
          linearDeep="accent"
          linear="right"
          label="联系客服"
        >
        </tm-button>
        <tm-button
          :margin="[30]"
          :round="10"
          v-else
          block
          :follow-theme="true"
          label="block"
          linearDeep="accent"
          linear="right"
          @click="startAdd"
          :label="state.getBtnLabel"
        >
        </tm-button>
        <tm-button
          :margin="[30]"
          :round="10"
          block
          outlined
          :follow-theme="true"
          label="block"
          linearDeep="accent"
          linear="right"
          @click="getInviteCode"
        >
          分享给朋友助力
        </tm-button>
        <view class="flex flex-row flex-row-center-center mt-n24">
          <tm-segtab
            :round="24"
            :width="getWidth(3)"
            color="indigo"
            :followTheme="true"
            v-model="state.current"
            activeColor="white"
            :list="state.list"
            :defaultValue="state.current"
            :gutter="0"
          ></tm-segtab>
        </view>

        <view class="mt-n5" v-if="state.current == 1">
          <tm-card
            :transprent="true"
            :border="true"
            v-for="item in state.giftInfo.empiricalRecordInfo"
            :margin="[32, 0, 32, 0]"
            :key="item.id"
            :title="item.marketingTitle"
          >
            <template v-slot:status>
              <tm-text color="#666" :fontSize="24">
                {{ item.createTime }}
              </tm-text>
            </template>
          </tm-card>
        </view>
        <view class="mt-n5" v-else>
          <tm-card
            :transprent="true"
            v-for="item in state.giftInfo.receiveRecordInfo"
            :margin="[32, 0, 32, 0]"
            :key="item.id"
            :title="item.userName"
          >
            <template v-slot:content>
              <view class="flex-center">
                <tm-text>助力商品：</tm-text>
                <tm-text
                  :followTheme="true"
                  _class="text-weight-b"
                  :fontSize="28"
                  :label="item.giftName"
                ></tm-text>
              </view>
            </template>
            <template v-slot:status>
              <tm-text color="#666" :fontSize="24">
                {{ item.createTime }}
              </tm-text>
            </template>
          </tm-card>
        </view>
      </view>
    </tm-sheet>

    <view class="flex flex-row flex-row-center-center mb-n10">
      <tm-text
        :font-size="28"
        color="#fff"
        linearDeep="accent"
        linear="right"
        @click="state.showGiftRule = true"
      >
        零元购规则
      </tm-text>
    </view>
    <tm-overlay v-model:show="state.showGiftRule" contentAnimation>
      <view @click.stop="">
        <tm-sheet
          :width="600"
          :follow-theme="true"
          :round="5"
          linearDeep="accent"
          linear="bottom"
          _style="overflow-y:scroll"
        >
          <view class="flex flex-row flex-row-center-center my-n5">
            <tm-text label="零元购规则" :font-size="40"></tm-text>
          </view>
          <scroll-view :scroll-top="0" :scroll-y="true" style="height: 500px">
            <tm-text
              :label="item.sysValue"
              _class="mt-n5"
              v-for="item in state.giftRule"
              :key="item.id"
            ></tm-text>
          </scroll-view>
        </tm-sheet>
      </view>
    </tm-overlay>
  </tm-app>
</template>

<script setup>
import { computed } from "@vue/reactivity";
import { reactive, watch } from "vue";
import {
  getMarketingRecordApi,
  getMarketingShareCodeApi,
  addEmpiricalByAdvertisingApi,
  getSignRegulationApi,
} from "@/api";
import { onLoad, onReady } from "@dcloudio/uni-app";

const state = reactive({
  percent: 0,
  // 规则弹窗
  showGiftRule: false,
  // 规则详情
  giftRule: [],
  current: "1",
  list: [
    { text: "积累记录", id: "1" },
    { text: "领取晒单记录", id: "2" },
  ],
  giftInfo: {
    // 经验值记录
    empiricalRecordInfo: [],
    // 商品详情
    marketingGiftInfo: {},
    // 进度详情
    marketingRecordInfo: {},
    // 领取详情
    receiveRecordInfo: [],
    // 剩余助力次数
    availableNumber: 10,
  },
  // 在页面中定义激励视频广告
  videoAd: null,
  // 广告是否看完
  addShowEnd: false,
  getBtnLabel: "",
});

const getWidth = (type = 1) => {
  const { torpx, getWindow } = uni.$tm.u;
  if (type == 1) {
    return torpx(getWindow().width) - 80;
  }
  if (type == 3) {
    return torpx(getWindow().width) - 140;
  }
  if (type == 2) {
    return torpx(getWindow().width) - 80 - 60;
  }
};

watch(
  () => state.giftInfo.availableNumber,
  (val) => {
    state.getBtnLabel =
      val == 0 ? "今日已上限，明日再来" : "观看视频增加经验值";
  },
  {
    immediate: true,
  }
);

watch(
  () => state.showGiftRule,
  async (val) => {
    if (val) {
      state.giftRule = await getSignRegulationApi();
    }
  }
);

onReady(() => {
  // 在页面onLoad回调事件中创建激励视频广告实例
  if (uni.createRewardedVideoAd) {
    state.videoAd = uni.createRewardedVideoAd({
      adUnitId: "adunit-ecc84ddcf39eb901",
    });
    state.videoAd.onLoad(() => {});
    state.videoAd.onError((err) => {});
    state.videoAd.onClose((res) => {
      state.addShowEnd = res.isEnded;
      if (!res.isEnded) {
        uni.showToast({
          icon: "error",
          title: "视频未播放完毕",
        });
      } else {
        startLookVideo();
      }
    });
  }
});

const startAdd = () => {
  // 用户触发广告后，显示激励视频广告
  if (state.videoAd) {
    state.videoAd.show().catch(() => {
      // 失败重试
      state.videoAd
        .load()
        .then(() => state.videoAd.show())
        .catch((err) => {
          console.log("激励视频 广告显示失败");
        });
    });
  }
};

onLoad(async ({ id }) => {
  if (!id) {
    uni.showToast({
      icon: "none",
      title: "参数错误",
    });
    uni.switchTab({
      url: "/pages/shop/shop",
    });
    return;
  }
  getGiftInfo(id);
});

/**
 * 获取礼物信息
 */
const getGiftInfo = async (giftId) => {
  state.giftInfo = await getMarketingRecordApi({ giftId });
  const { hasEmpirical, giftEmpirical } = state.giftInfo.marketingRecordInfo;
  state.percent = ((hasEmpirical / giftEmpirical) * 100).toFixed(2);
  state.giftInfo.marketingGiftInfo.images = state.giftInfo.marketingGiftInfo.giftPic.split(
    ","
  );
};

const startLookVideo = async () => {
  const giftId = state.giftInfo.marketingGiftInfo.id;
  await addEmpiricalByAdvertisingApi({
    marketingRecordId: state.giftInfo.marketingRecordInfo.id,
    giftId,
  });
  uni.showToast({
    icon: "success",
    title: "助力成功",
  });
  // 重新获取礼物信息
  getGiftInfo(giftId);
};

const getInviteCode = async () => {
  uni.navigateTo({
    url:
      "/shopPages/share-invite-code?marketingRecordId=" +
      state.giftInfo.marketingRecordInfo.id,
  });
};
</script>

<style></style>
